package com.cheng.xbsc.service.impl;

import com.cheng.xbsc.entity.Goods;
import com.cheng.xbsc.entity.Product;
import com.cheng.xbsc.mapper.GoodsMapper;
import com.cheng.xbsc.mapper.ProductMapper;
import com.cheng.xbsc.service.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class HomeServiceImpl implements HomeService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public List<Goods> findNewGoods() {
        return goodsMapper.findNewGoods();
    }

    @Override
    public List<Goods> findHotGoods() {
        Integer count = goodsMapper.countByStatus();
        return goodsMapper.findHotGoods(new Random().nextInt(count - 4));
    }

    @Override
    public List<Product> findAllProduct() {
        List<Product> productList = (List<Product>) redisTemplate.opsForValue()
                .get("com.cheng.xbsc.entity.Product:findAllProduct");
        if (productList != null) {
            return productList;
        }
        productList = productMapper.selectAll();
        redisTemplate.opsForValue()
                .set("com.cheng.xbsc.entity.Product:findAllProduct", productList, 60, TimeUnit.MINUTES);
        return productList;
    }
}
